/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "fr_local.h"
#include "gl_local.h"

#include <strstream>
#include <algorithm>

/*-----------------------------------------------------------------------------
	FRScene volume :
-----------------------------------------------------------------------------*/

//
//	EFRVolume::EFRVolume
//
EFRVolume::EFRVolume( class EFRScene *scene )
{
	this->scene		=	scene;
	matrix_world	=	EMatrix();
	
	bounds			=	EBBox(EPoint(), 1.0, 1.0, 1.0);
	range_lo		=	0.0;
	range_hi		=	1.0;

	int n = 256;
	std::vector<EColor> gray(n);
	for (int i = 0; i < n; ++i)
	{
		float c = (float)i / (n-1);
		gray[i] = EColor(c, c, c, c);
	}
	SetColormap(n, &gray[0]);

	ReloadShader();
}


//
//	EFRVolume::~EFRVolume
//
EFRVolume::~EFRVolume( void )
{

}


//
//	EFRVolume::ReloadShader
//
void EFRVolume::ReloadShader( void )
{
	effect = scene->fxm->CompileEffect("shaders/volume.cgfx");
}


//
//	EFRVolume::SetPose
//
void EFRVolume::SetPose( const EPoint &position, const EQuaternion &orient )
{
	EMatrix T		=	EMatrix::Translate( position.x, position.y, position.z );
	EMatrix R		=	orient.ToMatrix();

	matrix_world	=	R * T;

	if (atoms_entity)
		atoms_entity->SetPose(position, orient);
}

//
//	EFRVolume::Reload
//
void EFRVolume::Reload( void )
{
}


//
//	EFRVolume::Render
//
void EFRVolume::Render( IPxTexture depth )
{
	if (volume_tex == NULL)
		return;

	EVector s = bounds.Size();
	EMatrix Scale	=   EMatrix::Scale(s.x, s.y, s.z);
	EMatrix Pivot	=   EMatrix::Translate(EVector(bounds.Min()));

	EMatrix volume2local	=	Scale * Pivot;
	EMatrix model			=	volume2local * matrix_world;
	EMatrix	view			=	scene->view.matrix_view;
	EMatrix	proj			=	scene->proj.matrix_proj;
	EMatrix mvp				=	model * view * proj;

	effect->SetTechnique("tech_volume");
	effect->SetUniform("matrix", mvp );
	effect->SetUniform("matrix_mvp_inv", mvp.Inverse() );
	effect->SetUniform("matrix_modelview_inv", (model * view).Inverse() );
	effect->SetUniform("mtx_volume2local", volume2local );

	effect->SetTexture("volume_tex", volume_tex);
	int w = volume_tex->GetWidth();
	int h = volume_tex->GetHeight();
	int d = volume_tex->GetDepth();
	effect->SetUniform("volume_size", EPoint(w, h, d) );

	effect->SetUniform("volume_ofs", EPoint(0.5/w, 0.5/h, 0.5/d) );
	effect->SetUniform("volume_scale", EPoint(1-1.0/w, 1-1.0/h, 1-1.0/d) );

	effect->SetTexture("depth_tex", depth);
	effect->SetTexture("colormap_tex", colormap_tex);
	effect->SetTexture("preintegrated_tex", preintegrated_tex);

	float cm_pad = 0.5 / colormap_tex->GetWidth();
	float transfer_scale = (1.0 - 2*cm_pad) / (range_hi - range_lo);
	float transfer_offset = cm_pad - transfer_scale*range_lo;
	effect->SetUniform("transfer_scale", transfer_scale);
	effect->SetUniform("transfer_offset", transfer_offset);

	EUIQuad q;
	q.color = EColor::kWhite;
	q.p0 = EPoint(-1, -1);
	q.p1 = EPoint( 1,  1);
	q.uv0  = ETexCoord(0, 1);
	q.uv1  = ETexCoord(1, 0);
	
	uint n;	
	effect->Begin(n);
		for (uint i=0; i<n; i++) {
			effect->BeginPass(i);
			scene->driver->GetVBM()->DrawQuads( 1, &q );
			effect->EndPass();
		}		
	effect->End();
}


//
//	EFRVolume::LoadFromCube
//
void EFRVolume::LoadFromCube( const EString &path )
{
	LOGF("Loading : %s", path.CStr());

	IHrFile f = fs()->openFile(path.CStr(), FS_OPEN_READ);
	std::vector<char>	buf;
	buf.resize(f->size()+1, '\0');
	f->read(&buf[0], f->size());
	f = NULL;

	std::istrstream ss(&buf[0]);
	std::string s;

	// skip two line header
	std::getline(ss, s);
	std::getline(ss, s);

	EPoint p;
	EVector e0, e1, e2;
	int atom_count = 0;
	int w, h, d;
	ss >> atom_count >> p.x >> p.y >> p.z;
	ss >> w >> e0.x >> e0.y >> e0.z;
	ss >> h >> e1.x >> e1.y >> e1.z;
	ss >> d >> e2.x >> e2.y >> e2.z;

	IPxTriMesh atoms = Geometry()->CreateTriMesh( GE_MESH_POSITION | GE_MESH_NORMAL );
	for (int i = 0; i < atom_count; ++i)
	{
		int atom_id;
		float r, x, y, z;
		ss >> atom_id >> r >> x >> y >> z;

		IPxTriMesh sphere = Geometry()->CreateSphere(r*0.1, 8, 4);
		sphere->Transform(EMatrix::Translate(x, y, z));
		atoms->Merge(sphere);
	}
	EShadingGroup sg;
	sg.start = 0;
	sg.num = atoms->GetTriangleNum();
	sg.shader = "*color808080FF";
	atoms->AttachSG(sg);
	
	atoms_entity = scene->AddEntity();
	atoms_entity->SetMesh(atoms);
	
	std::vector<float> data(w*h*d);
	for (int ix = 0; ix < w; ++ix)
	for (int iy = 0; iy < h; ++iy)
	for (int iz = 0; iz < d; ++iz)
	{
		ss >> data[ix + iy*w + iz*w*h];
	}

	float lo = *std::min_element(data.begin(), data.end());
	float hi = *std::max_element(data.begin(), data.end());

	volume_tex = EGLTexture::CreateVolumeF(w, h, d, &data[0]);
	SetInterestRange(lo, hi);

	EBBox box(p, p + e0*w + e1*h + e2*d);
	SetBounds(box);
}

void EFRVolume::LoadFromRAW( const EString &path, int w, int h, int d  )
{
	LOGF("Loading : %s", path.CStr());

	IHrFile f = fs()->openFile(path.CStr(), FS_OPEN_READ);
	std::vector<unsigned char>	buffer;
	int size = f->size();
	if (size != w*h*d)
		RUNTIME_ERROR("w*h*d != file_size");

	buffer.resize(size, '\0');
	f->read(&buffer[0], size);
	f = NULL;

	std::vector<float> buffer_float(size);
	for (int i = 0; i < size; ++i)
		buffer_float[i] = buffer[i] / 255.0f;

	volume_tex = EGLTexture::CreateVolumeF(w, h, d, &buffer_float[0]);
}

void EFRVolume::LoadColormap( const EString &path )
{
	LOGF("Loading : %s", path.CStr());
	IPxImage img = ifct()->LoadImageFromFile(path);
	std::vector<EColor> cmap(img->GetWidth());
	for (int i = 0; i < cmap.size(); ++i)
		cmap[i] = img->Sample(i, 0, false);
	SetColormap(cmap.size(), &cmap[0]);
}


void EFRVolume::SetBounds( const EBBox &box )
{
	bounds = box;
}

void EFRVolume::SetColormap( int n, const EColor *colors )
{
	colormap.assign(colors, colors + n);
	colormap_tex = EGLTexture::CreateColormapTexture( n, colors );
	PreintegrateColormap();
}

void EFRVolume::SetInterestRange( float lo, float hi )
{
	range_lo = lo;
	range_hi = hi;
}

void EFRVolume::SetResolution( uint res_x, uint res_y, uint res_z )
{
	std::vector<float> zeros(res_x * res_y * res_z, 0.0f);
	volume_tex = EGLTexture::CreateVolumeF(res_x, res_y, res_z, &zeros[0]);
}

void EFRVolume::UpdateData( const DataProvider *provider )
{
	int w = volume_tex->GetWidth();
	int h = volume_tex->GetHeight();
	int d = volume_tex->GetDepth();

	EVector sz = bounds.Size();
	float dx = sz.x / (w-1);
	float dy = sz.y / (h-1);
	float dz = sz.z / (d-1);

	std::vector<float> buf(w*h*d);
	int ofs = 0;
	for (int iz = 0; iz < d; ++iz)
	for (int iy = 0; iy < h; ++iy)
	for (int ix = 0; ix < w; ++ix, ++ofs)
	{
		EPoint p = bounds.Min() + EVector(ix*dx, iy*dy, iz*dz);
		buf[ofs] = provider->Value(p);
	}
	volume_tex->WriteDataRaw3D(&buf[0]);
}

inline EColor adjust_alpha(EColor c, float step)
{
	c.a = 1.0 - powf(1.0 - c.a, step);
	c.r *= c.a;
	c.g *= c.a;
	c.b *= c.a;
	return c;
}
inline EColor blend(const EColor &a, const EColor &b)
{
	return a + b * (1.0 - a.a);
}

inline EColor unblend(const EColor &a, const EColor &c)
{
	return (c - a) / (1.0 - a.a);
}

void EFRVolume::PreintegrateColormap()
{
	int n = colormap.size();
	// table(x, y) - ray from x to y
	IPxImage table = ifct()->CreateImage(n, n, EColor(0, 0, 0, 0));
	for (int i = 0; i < n; ++i)
		table->WritePixel(i, i, adjust_alpha(colormap[i], 1.0));
	
	std::vector<EColor> adj_cmap(n);
	for (int d = 1; d < n; ++d)
	{
		float step = 1.0 / (d+1);
		for (int i = 0; i < n; ++i)
			adj_cmap[i] = adjust_alpha(colormap[i], step);
		for (int i = 0; i < d; ++i)
		{
			EColor c_0d = table->Sample(0, d, false);
			EColor c_d0 = table->Sample(d, 0, false);
			table->WritePixel(0, d, blend(c_0d, adj_cmap[i]));
			table->WritePixel(0, d, blend(adj_cmap[i], c_d0));
		}

		for (int i = 0; i < n-d; ++i)
		{
			int j = i + d;
			EColor c_ij = table->Sample(i, j, false);
			EColor c_ji = table->Sample(j, i, false);
			/*table->WritePixel(i+1, j+1, blend( unblend(adj_cmap[i], c_ij), adj_cmap[j+1]) );
			table->WritePixel(j+1, i+1, blend( unblend(adj_cmap[j], c_ji), adj_cmap[i+1]) );*/
			for (int k = 0; k < d+1; ++k)
			{
				c_ij = blend(c_ij, adj_cmap[i+k]);
				c_ji = blend(adj_cmap[i+k], c_ji);
			}
			table->WritePixel(i, j, c_ij);
			table->WritePixel(j, i, c_ji);


		}
	}

	IPxBlob blob = table->GetByteRGBABlob();
	ifct()->SaveImageToFile("volume/preint.png", 1, n, n, 32, blob->GetBufferPointer());

	preintegrated_tex = EGLTexture::LoadTextureFromImage(table);
}